package com.jxpanda.starter.config.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import com.jxpanda.commons.toolkit.ObjectKit;
import com.jxpanda.commons.toolkit.StringKit;
import com.jxpanda.commons.toolkit.json.JsonKit;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.codec.DecoderHttpMessageReader;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import javax.annotation.Resource;

/**
 * @author Panda
 */
@Configuration
@ComponentScan
@EnableConfigurationProperties(CommonProperties.class)
public class AutoConfiguration implements WebFluxConfigurer {

    @Resource
    private CommonProperties commonProperties;

    @Bean
    public ObjectMapper jackson() {
        CommonProperties.Json jsonConfig = commonProperties.getJson();
        if (ObjectKit.isNotEmpty(jsonConfig.getImageDomain())) {
            JsonKit.registerImageModule(jsonConfig.getImageDomain());
        }
        if (ObjectKit.isNotEmpty(jsonConfig.getProxyFields())) {
            jsonConfig.getProxyFields().forEach(JsonKit::addImageField);
        }
        return JsonKit.jackson();
    }

    @Bean
    public JsonMessageConverter jsonMessageConverter() {
        return new JsonMessageConverter(jackson());
    }

    @Bean
    public Jackson2JsonEncoder jackson2JsonEncoder() {
        return new Jackson2JsonEncoder(jackson(), MediaType.APPLICATION_JSON);
    }

    @Bean
    public Jackson2JsonDecoder jackson2JsonDecoder() {
        return new Jackson2JsonDecoder(jackson(), MediaType.APPLICATION_JSON);
    }

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.customCodecs().register(new DecoderHttpMessageReader<>(jackson2JsonDecoder()));
        configurer.customCodecs().register(new EncoderHttpMessageWriter<>(jackson2JsonEncoder()));
        configurer.defaultCodecs().maxInMemorySize(commonProperties.getMaxInMemorySize());
    }


}
